package fa7.socialcode.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import fa7.socialcode.dao.AvaliacaoDao;
import fa7.socialcode.model.Avaliacao;
import fa7.socialcode.model.Example;

@Repository(value = "avaliacaoDao")
public class AvaliacaoDaoHibernate implements AvaliacaoDao {
  HibernateTemplate hibernateTemplate;
  //Somente para log
  Log logger = LogFactory.getLog(AvaliacaoDaoHibernate.class);

  @Autowired
  public AvaliacaoDaoHibernate(SessionFactory sessionFactory) {
    this.hibernateTemplate = new HibernateTemplate(sessionFactory);
  }

  @Override
  public Avaliacao findAvaliacao(Long id) {
    Avaliacao avaliacao = 
      (Avaliacao) hibernateTemplate.get(Avaliacao.class, id);
    if (avaliacao == null) {
        throw new ObjectRetrievalFailureException(Avaliacao.class, id);
    }
    return avaliacao;
  }

  @Override
  public List findAvaliacoes() {
      return hibernateTemplate.find("from Avaliacao");
  }

  @Override
  public void removeAvaliacao(Long Id) {
      hibernateTemplate.delete(findAvaliacao(Id));

  }

  @Override
  public void removeAvaliacao(Avaliacao avaliacao) {
      hibernateTemplate.delete(findAvaliacao(avaliacao.getId()));

  }

  @Override
  public void saveAvaliacao(Avaliacao avaliacao) {
      hibernateTemplate.saveOrUpdate(avaliacao);

      if (logger.isDebugEnabled()) {
          logger.debug("avaliacaoId set to: " + avaliacao.getId());
      }
  }

}
